package thread;

/**
 * @author xiongf
 * 实现子线程循环5次，主线程循环10次，
 * 然后再子线程循环5此，主线程循环10次
 * 以此类推
 *
 */
public class ThreadCommuncation {

	static Business business = new Business();

	public static void main(String[] args) {
		SubTherad subtherad = new SubTherad();
		Thread subThread = new Thread(subtherad);

		MainThread mainthread = new MainThread();
		Thread mainThread = new Thread(mainthread);
		subThread.start();
		mainThread.start();
	}
}

class SubTherad implements Runnable {
	@Override
	public void run() {
		while (true) {
			// synchronized (this) {
			ThreadCommuncation.business.subThread();
			// }
		}
	}
}

class MainThread implements Runnable {

	@Override
	public void run() {
		while (true) {
			// synchronized (this) {
			ThreadCommuncation.business.mainThread();
			// }
		}
	}
}

class Business {
	private static boolean isSub = true;

	public synchronized void mainThread() {
		while (isSub) {
			try {
				// 在这里方法synchronized了什么，this这里就是什么，
				// 如此方法synchronized的是this对象，所以这里写this
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int j = 1; j < 11; j++) {
			try {
				Thread.sleep(500L);
				System.out.println("mainthread---" + j);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		isSub = true;
		this.notify();
	}

	public synchronized void subThread() {
		while (!isSub) {
			try {
				// 在这里方法synchronized了什么，this这里就写什么，
				// 如此方法synchronized的是this对象，所以这里写this
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int j = 1; j < 6; j++) {
			try {
				Thread.sleep(500L);
				System.out.println("subthread---" + j);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		isSub = false;
		this.notify();
	}
}
